package com.coolwen.controller;

import com.alibaba.fastjson.JSON;
import com.coolwen.entity.Address;
import com.coolwen.entity.Resource;
import com.coolwen.entity.Role;
import com.coolwen.entity.User;
import com.coolwen.service.AddressService;
import com.coolwen.service.RoleService;
import com.coolwen.service.UserService;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by user on 2016/6/29.
 */
@Controller
@RequestMapping("/admin/user/")
public class UserController {

    private Logger logger = Logger.getLogger(getClass());

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private AddressService addService;

    @RequestMapping("list")
    public String list(Model model, String con, HttpServletRequest req) throws UnsupportedEncodingException {
        if (con != null) {
            String conn = req.getParameter("con");

            logger.info("查找用户信息:" + con);
            model.addAttribute("con", con);
            model.addAttribute("pagers", userService.find(con));
        } else
//        model.addAttribute("users", userService.list());
        {

//            Subject currentUser = SecurityUtils.getSubject();
//            User loginUser = (User) currentUser.getPrincipals().getPrimaryPrincipal();
            //           currentUser.getSession();
//            Subject currentUser = SecurityUtils.getSubject();//获取当前用户
//            currentUser.getSession();  //获取会话
//            currentUser.checkPermission("printer:print");//检查是否有对应权限
//            currentUser.checkRole("管理员");//检查是否有对应角色
//            currentUser.logout(); //执行登出操作,移除对应的session以及权限数据。
//            logger.info("查找用户信息getPrincipals:" + JSON.toJSON(currentUser.getPrincipals()));
//            logger.info("查找用户信息currentUser:" + JSON.toJSON(currentUser.getPrincipals()));
//            logger.info("查找用户信息currentUser:" + JSON.toJSON(loginUser));
            model.addAttribute("pagers", userService.find(null));
        }
        return "user/list";
    }

    @RequestMapping(value = "add", method = RequestMethod.GET)
    public String add(Model model) {
        model.addAttribute("user", new User());
        model.addAttribute("roles", roleService.list());
        return "user/add";
    }

    @RequestMapping(value = "add", method = RequestMethod.POST)
    public String add(User user, BindingResult br, HttpServletRequest req) {
        if (br.hasErrors()) {
            //如果有错误直接跳转到add视图
            return "/user/add";
        }
        String[] trids = req.getParameterValues("rids");
        logger.info("查找rids:" + JSON.toJSON(trids));
        List<Integer> rids = new ArrayList<Integer>();
        if (trids != null) {
            for (String rid : trids) {
                rids.add(Integer.parseInt(rid));
            }
//            logger.info("查找rids:" + JSON.toJSON(rids));
        }
        userService.add(user, rids);
        return "redirect:/admin/user/list";
    }

    @RequestMapping("updateStatus/{id}")
    public String updateStatus(@PathVariable int id) {

        //只更新用户状态
        User u = new User();
        User user = userService.load(id);
        u.setStatus(user.getStatus());
        u.setId(user.getId());
        //       logger.info("updateStatus配置Controller:" + JSON.toJSON(u));
        if (u.getStatus()) {
            u.setStatus(false);
        } else {
            u.setStatus(true);
        }
        userService.update(u);
        return "redirect:/admin/user/list";
    }

    @RequestMapping(value = "update/{id}", method = RequestMethod.GET)
    public String update(@PathVariable int id, Model model) {
        User user = userService.load(id);
        //       logger.info("update配置Controller:" + JSON.toJSON(user));
        model.addAttribute("user", user);
        model.addAttribute("roles", roleService.list());
        List<Role> hasRoles = userService.loadUserRole(id).getRoles();
        List<Integer> rids = new ArrayList<Integer>();
        for (Role r : hasRoles) {
            rids.add(r.getId().intValue());
        }
        model.addAttribute("hasRole", rids);
        //       logger.info("配置rids:" + JSON.toJSON(hasRoles));
        //       logger.info("配置rids:" + JSON.toJSON(rids));
        return "user/update";
    }

    @RequestMapping(value = "update/{id}", method = RequestMethod.POST)
    public String update(@PathVariable int id, HttpServletRequest req, User user) {
//        userService.load(id);
//        logger.info("配置rids:" + JSON.toJSON(user));
//        logger.info("update配置U:" + JSON.toJSON(user));
        User tu = userService.load(id);
        tu.setNickname(user.getNickname());
        tu.setPassword(user.getPassword());
        tu.setUsername(user.getUsername());
        //       tu.setLocked(user.getLocked());
        String[] trids = req.getParameterValues("rids");
        List<Integer> rids = null;
        if (trids != null) {
            rids = new ArrayList<Integer>();
            for (String rid : trids) {
                rids.add(Integer.parseInt(rid));
            }
        }
//        logger.info("update配置TU:" + JSON.toJSON(tu) + "update配置TU:rids" + rids);
        userService.update(tu, rids);
        return "redirect:/admin/user/show";
    }

    @RequestMapping("/listRes/{id}")
    public String listRes(Model model, @PathVariable int id) {
        List<Resource> hasRes = userService.listUserRes(id);
        model.addAttribute("reses", hasRes);
        model.addAttribute("user", userService.load(id));
        return "user/res";
    }

    @RequestMapping("/{id}")
    public String listUser(Model model, @PathVariable int id) {

        User u = userService.load(id);
        Subject currentUser = SecurityUtils.getSubject();
        User loginUser = (User) currentUser.getPrincipals().getPrimaryPrincipal();
        List<Address> addresses = addService.listByUid(u.getId());
        u.setAddresses(addresses);
        logger.info("address配置:" + JSON.toJSON(addresses));

        logger.info("user配置:" + JSON.toJSON(u));
        model.addAttribute("user", u);
        model.addAttribute("loginUser", loginUser);

        return "user/user";
    }

    @RequestMapping("show")
    public String showUser(Model model) {
        Subject currentUser = SecurityUtils.getSubject();
        User loginUser = (User) currentUser.getPrincipals().getPrimaryPrincipal();
        List<Address> addresses = addService.listByUid(loginUser.getId());
        loginUser.setAddresses(addresses);
        model.addAttribute("loginUser", loginUser);
        model.addAttribute("user", loginUser);
        return "user/user";
    }

    @RequestMapping(value = "updateSelf", method = RequestMethod.GET)
    public String updateSelf(Model model) {

        Subject currentUser = SecurityUtils.getSubject();
        User loginUser = (User) currentUser.getPrincipals().getPrimaryPrincipal();
        model.addAttribute("user", loginUser);
        return "user/updateSelf";
    }

    @RequestMapping(value = "updateSelf", method = RequestMethod.POST)
    public String updateSelf(User user, Model model) {

        Subject currentUser = SecurityUtils.getSubject();
        User loginUser = (User) currentUser.getPrincipals().getPrimaryPrincipal();
        User tu = userService.load(loginUser.getId());
        tu.setNickname(user.getNickname());
        tu.setPassword(user.getPassword());
        tu.setUsername(user.getUsername());
        userService.update(tu);
        return "redirect:/admin/user/addProductNumber";
    }
}
